<template>
  <div style="height: 100%;background-color: white">
    <div class="custBox">
      <div class="operation">
        <div class="operation_left">
          <span v-show="select_num == 0">共{{total}}个客户</span>
          <span v-show="select_num > 0">已选中{{select_num}}个</span>
          <el-button size="mini" style="margin: 0 5px" @click="senMail" :disabled="select_num == 0"
                     v-if="jurisdiction.subordinate_customer_sendMail">发送邮件
          </el-button>
          <el-button size="mini" style="margin: 0 5px" @click="dealingsMail" :disabled="edit_boolean"
                     v-if="jurisdiction.subordinate_customer_exchange">来往邮件
          </el-button>
        </div>
        <div class="operation_right search">
          <el-autocomplete
            size="mini"
            class="inline-input"
            style="width:220px;margin: 0 10px"
            v-model="input"
            @keyup.enter.native="search"
            @change="replace"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            placeholder="请输入客户名称/联系人/邮箱查询">
            <el-button slot="append" style="cursor: pointer;" @click="search">
              <i class="el-icon-search"></i>
            </el-button>
          </el-autocomplete>
          <el-button size="mini" @click="advancedSearch()">高级搜索</el-button>
        </div>
      </div>
      <div style="background-color:white">
        <div class="btns" v-show="senior">
          <div style="width: 96px;padding-top: 7px">
            <span style="color:#232323">标签：</span>
            <label style="margin:0 4px;">
              <input type="checkbox" style="height:1px;width:1px;display:none">
              <span class="lable_checkbox" @click="checkbox($event, 'lable', markList)" onselectstart="return false"
                    :class="lables.length == markList.length ? 'checkbox_active' : ''"></span>
            </label> <span>全部</span>
          </div>
          <div>
            <span class="btn_item_lable" v-for="(item,index) in markList"
                  :class="lables.includes(item.id) ? 'activeBtn': ''" :key="index" onselectstart="return false"
                  @click="active($event, 'label', item.id)">{{item.markName}}</span>
          </div>
        </div>
      </div>
      <!--客户列表显示字段设置-->
      <el-dialog
        :close-on-click-modal="false" :close-on-press-escape='false'
        :visible.sync="centerDialogVisible"
        width="300px"
        append-to-body
        :show-close="true"
        @close="closeCustShow"
        center>
          <span slot="title" class="dialog-title">
            客户列表显示字段设置
          </span>
        <div style="height: 300px">
          <el-checkbox-group v-model="copyCheckList" :min="1" @change="changeCheck">
            <div v-for="(value,index3) in showlist" :key="index3" style="padding-left: 85px;margin: 5px 0">
              <el-checkbox :label="value.name" :disabled="value.name =='客户名称' "></el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="closeCustShow" size="small" type="primary" plain>取 消</el-button>
            <el-button type="primary" @click="custShow" :loading="loading" size="small">保存</el-button>
          </span>
      </el-dialog>
      <div class="table_box">
        <div class="icon icon_left">
          <span class="icon-shaixuan" @click="centerDialogVisible = true"></span>
        </div>
        <el-table
          v-if="load"
          :header-row-style="{background:'#EAF0F6'}"
          ref="multipleTable"
          :data="tableData"
          @selection-change='selectList'
          :row-style="rowClass"
          tooltip-effect="dark"
          style="width: 100%"
          :height="tableHeight"
          class="table"
          @sort-change="sortChange"
          @row-click="preview">
          <el-table-column
            type="selection"
            :fixed="true"
            width="55">
          </el-table-column>
          <template v-for="(col, index) in headerList">
            <el-table-column
              :width="col.field == 'light' ? 80 : 200"
              :label="col.name"
            >
              <template slot-scope="scope">
                <tableTemplate :col="scope.row" :label="col.field" :jurisdiction="jurisdiction" @jump="toDetail" custType="subordinate"></tableTemplate>
              </template>
            </el-table-column>
          </template>

          <el-table-column
            width="40"
            fixed="right">
          </el-table-column>
          <div slot="empty" style="width: 100%;text-align: left;margin-lrft:-250px">
            <div>
              <img :src="empty" alt="" style="width: 250px"/>
            </div>
          </div>
        </el-table>
      </div>
      <div class="footer">
        <el-pagination align="right"
                       class="fixed"
                       v-show="total>0"
                       style="minHeight:30px"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page.sync="nowPage"
                       :page-sizes="[10, 20, 30, 50]"
                       :page-size="nowSize"
                       layout=" prev,pager, next,  sizes"
                       :total="total">
        </el-pagination>
      </div>
      <!-- 标记客户 -->
      <el-dialog :close-on-press-escape='false'
                 :visible.sync="markDialog"
                 width="500px"
                 align="center"
                 style="font-size: 13px"
                 :close-on-click-modal="false"
                 @close="cancelMark"
                 append-to-body>
        <span slot="title" class="dialog-title">
          <span style="color:#2A97F9">标记客户</span>
        </span>
        <div style="padding:50px 0">
          <div class="flex">
            <span>标记为：</span>
            <el-select v-model="markArr" multiple placeholder="请选择" size="small" @change="openAddMark"
                       v-if="markDialog">
              <el-option
                v-for="item in lableList"
                :key="item.id"
                :label="item.markName"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelMark" size="small">取 消</el-button>
          <el-button type="primary" @click="custSaveMark" size="small">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 弹窗新增客户-->
      <editCompany ref="editCompany" v-if="logShow" v-bind:show="editCom_show" @updata="updataCompany" :email="[]"
                   :title="editCom_title" :id="custId"
                   :defaultType="typeId" :userId="userId"></editCompany>
      <!--   合并客户   -->
      <el-dialog :close-on-press-escape='false'
                 :visible.sync="signDialog"
                 width="500px"
                 center
                 :close-on-click-modal="false"
                 append-to-body>
        <span slot="title" class="dialog-title">
          <span style="color:#2A97F9">合并客户</span>
        </span>
        <div class="center_left">
          <span style="margin-right:20px">待合并客户:</span>
          <div style="padding-left:40px">

            <el-radio-group v-model="priKey">
              <el-radio v-for="(item, index) in selectData" :key="index" :label="item.fullname">{{item.fullname}}
              </el-radio>
            </el-radio-group>

          </div>
        </div>
        <div style="margin-top:20px" class="center_left">
          <span class="el-icon-warning-outline"></span>
          <span>   客户资料冲突时，将会以主客户（{{priKey}}） 的资料为准！</span>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="signDialog = false">取 消</el-button>
          <el-button type="primary" @click="mergeCust">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 转移客户 -->
      <el-dialog :visible.sync="transferDialog"
                 center append-to-body width="480px"
                 :close-on-click-modal="false" :close-on-press-escape='false'
                 style="font-size:13px" :before-close="cancelTransfer">
        <p slot="title" class="dialog-title">转移客户</p>
        <div class="operation_box">
          <div class="operation_information">将这（{{selectData.length}}位）客户转移给：</div>
          <div>
            <el-select v-model="transferArr" multiple placeholder="请选择" size="small">
              <el-option
                v-for="item in userTree"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>

        <div class="cust_content">
          <div style="flex: 0 0 100px">
            <span>被转移的客户：</span>
          </div>
          <div>
                <span v-for="(item, index) in selectData" :key="index">
              <span v-if="index > 0">.</span>
              {{item.fullname}}</span>
          </div>
        </div>
        <p>
          <span class="icon-iconfontxiaogantanhao"></span>
          <span>客户转移给他人后，将会从我的客户列表中删除，对方将可见该客户的全部资料。</span>
        </p>

        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelTransfer" size="small">取 消</el-button>
          <el-button type="primary" @click="transferCust" size="small">转 移</el-button>
        </div>
      </el-dialog>

      <!-- 共享客户 -->
      <el-dialog :visible.sync="shareDialog"
                 :close-on-click-modal="false" :close-on-press-escape='false'
                 center append-to-body width="500px"
                 style="font-size:13px" :before-close="cancelShare">
        <p slot="title" class="dialog-title">共享客户</p>
        <div class="operation_box">
          <div class="operation_information">将这（{{selectData.length}}位）客户共享给：</div>
          <div>
            <el-select v-model="transferArr" multiple placeholder="请选择" size="small">
              <el-option
                v-for="item in userTree"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>

        <div class="cust_content">
          <div style="flex: 0 0 100px">
            <span>被共享的客户：</span>
          </div>
          <div>
            <span v-for="(item, index) in selectData" :key="index" :label="item.fullname">
              <span v-if="index > 0">.</span>
              {{item.fullname}}</span>
          </div>
        </div>
        <p>
          <span class="icon-iconfontxiaogantanhao"></span>
          <span>客户共享后，将同时出现在我和被共享人的客户列表中。客户资料共享。</span>
        </p>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelShare" size="small">取 消</el-button>
          <el-button type="primary" @click="sharedCust" size="small">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 新建标签并标记 -->
      <el-dialog :visible.sync="label_show" center append-to-body width="415px" :close-on-click-modal="false"
                 @close="cancelLabel"
                 style="font-size:13px" :close-on-press-escape='false'>
        <p slot="title" class="dialog-title">标签</p>
        <div class="flex">
          <span>标签名称：</span>
          <el-input v-model="markName" autocomplete="off" style="width:230px" maxlength="10"></el-input>
          <el-button style="width:38px;height:38px;textalign:center;padding:0" @click.stop="cloorPicker"
                     v-bind:style="{background: colorBg}">
            <i class="el-icon-arrow-down"></i>
          </el-button>
          <div class="colorList" @click.stop="selectColor" v-show="cloorPickerShow">
            <ul>
              <li v-for="(item, index) in colorArray" :key=index v-bind:style="{background: item}"
                  class="colorItem"></li>
            </ul>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelLabel" size="small">取 消</el-button>
          <el-button type="primary" @click="addMark" size="small">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 取消跟进 -->
      <el-dialog :visible.sync="cancel_show"
                 :close-on-press-escape='false'
                 center append-to-body width="500px"
                 :close-on-click-modal="false">
        <p slot="title" class="dialog-title">取消跟进客户</p>
        <div style="font-size:13px;text-align: center;line-height: 20px">
          <p style="font-weight: 600">您确定要取消跟进如下{{selectName.length}}个客户吗？</p>
          <p style="margin-top: 5px">
            <span style="font-weight: 600" v-for="(item,index) in selectName" :key="index"> <span
              v-if="index != 0">,</span>{{item}} </span>
          </p>

        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel_show = false" size="small">取　　消</el-button>
          <el-button type="primary" @click="cancelCust" size="small">取消跟进</el-button>
        </div>
      </el-dialog>
      <!-- 删除客户 -->
      <el-dialog :visible.sync="delete_show" center
                 append-to-body width="400px"
                 :close-on-click-modal="false" :close-on-press-escape='false'
      >
        <p slot="title" class="dialog-title">删除客户</p>
        <div style="font-size:13px;text-align: center;line-height: 20px">
          <p style="font-weight: 600">您确定要删除如下{{selectName.length}}个客户吗？</p>
          <p style="margin-top: 5px" class="moreLine">
            <span style="font-weight: 600" v-for="(item,index) in selectName" :key="index"> <span
              v-if="index != 0">,</span>{{item}} </span>
          </p>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="delete_show = false" size="small">取消</el-button>
          <el-button type="primary" @click="deleteCust" size="small">确定</el-button>
        </div>
      </el-dialog>
      <!--   右侧抽屉   -->
      <drawer v-if="drawerShow" :custId="nowId" :visible="visShow" @callback="closeDrawer" type="2"
              :typeId="userId"></drawer>
      <!--选择联系人-->
      <DialogLinker ref="dialogLinker"></DialogLinker>
    </div>
  </div>
</template>
<script>
    import tableTemplate from '@/components/customer/tableTemplate'
    import editCompany from '@/components/customer/company'
    import Mail from '@/views/mail/draft/edit'
    import DialogLinker from '@/components/customer/dialogLinker'
    import {
        querySubCust,
        lightCustInfo,
        queryCustMark,
        saveCustMark,
        deleteBatchCust,
        markCust,
        moveGroup,
        mergeCust,
        queryCust,
        shareCust,
        transferCust,
        queryCustType,
        getCustField,
        setCustField,
        getFlowUp,
        cancelFlowUp,
        delMarkCust,
        fullNameStore,
        findUserByCrop
    } from '@/api/customer'
    import {getCustomerEmail} from '@/util/util'
    import drawer from './template/drawer'

    import {mapGetters, mapState} from 'vuex'

    export default {
        data() {
            return {
                empty: './img/empty.png',
                load: false,
                jurisdiction: {}, // 权限集合
                drawerShow: false, // 详情页组件
                visShow: false, // 抽屉显隐
                nowId: '', // 当前客户id
                markDialog: false,
                send_mail_show: false, // 发送邮件弹框
                edit_boolean: true, // 是否可以编辑
                label_show: false, // 新建标签的显示
                cloorPickerShow: '', // 颜色选择
                colorBg: '', // 背景选择颜色
                colorArray: ['#000000', '#BE5957', '#DA762F', '#139891', '#4A669F', '#595AC1', '#333333', '#E63C38', '#EC994D', '#5DBD7F', '#5B87ED', '#8D50BF', '#7B8291', '#F07A79', '#E3AE02', '#7EC65E', '#45A7EE', '#ACACAC'],
                editCom_show: false, // 修改客户弹框
                editCom_title: '编辑客户',
                centerDialogVisible: false, // 表头显示
                checkList: [], // 显示表头数组
                copyCheckList: [], // 深拷贝复制选择
                headerList:[], // 选中表头集合，用来遍历表头
                edittacts_show: false,
                markList: [], // 标记为
                showlist: [], // 显示表头数组
                dialogFormVisible: false,
                select_num: 0, // 多选的条数
                total: 0, // 总条数
                nowpage: 1, // 当前页
                input: '', // 输入框
                value: '',
                tableData: [],
                activeName: 'second',
                size: 'medium',
                selectData: [], // 多选数组
                selectIds: [], // 多选ids
                selectName: [], // 多选姓名
                selectRow: [],
                signDialog: false,
                transferDialog: false,
                selectTitle: '', // 树形select框title
                shareDialog: false,
                cancel_show: false,
                selectionId: '',
                selectValue: '',
                mergeOptions: [],
                senior: false,
                lableList: [],
                groupingList: [],
                group_num: 0,
                lable_num: 0,
                delete_show: false,
                nowData: '', // 当前右键所选中的数据
                nowSize: 10, //当前页显示条数
                markName: '',
                delete_type: '', // 删除状态，控制单删还是多选删除
                markDto: [], // 标记为的数组
                markArr: [], // 标记id组
                editData: '',
                followContent: '', // 跟进内容
                editCon_title: '',
                contactsData: '',
                contactsIndex: '', // 当前编辑联系人的索引
                userOptions: [], // 当前企业下所有用户
                shareValue: [], // 共享数组
                transferValue: [], // 分享数组
                custTypeOptions: [], // 当前用户的所有分组
                isPublic: '', // 是否是公海客户
                custType: '', // 客户分组类型
                userId: this.$route.params.userId, // 下属客户id
                props: {
                    value: "id",
                    label: "folderName",
                    children: "children"
                },
                isClearable: true, // 可清空（可选）
                isAccordion: true, // 可收起（可选）
                sortField: '', // 排序的id
                sortType: '', // 排序方式 （正序倒序）
                treeShow: true,
                defaultEmail: [],
                priKey: '', // 合并客户的主要客户
                typeids: [], // 分组id集合
                lables: [], // 标签id集合
                userTree: [], // 共享，转移数组
                flowUpList: [], // 跟进记录信息
                flowUpTotal: 0, // 跟进记录条数
                flowUpContent: '', // 跟进记录搜索
                tiemOptions: [{
                    value: 'ASC',
                    label: '时间正序'
                },
                    {
                        value: 'DESC',
                        label: '时间倒序'
                    },
                ],
                flowUpType: 0, // 默认事类型为全部
                timeSort: 'DESC', // 默认时间顺序为倒序
                nowPage: 1,
                custId: '',
                companyShow: false,   // 强制刷新组件的方法
                tips: [],
                manager: '',
                shareArr: [], // 分享的数组
                transferArr: [], // 转移的数组
                typeId: this.$route.params.typeId ? this.$route.params.typeId : '',
                logShow: false,
                HEIGHT: '',
                tableHeight: document.documentElement.clientHeight - 177,
                loading:false
            }
        },
        computed: {
            ...mapState(['common']),
            ...mapGetters(["permission"]),
        },
        watch: {
            selectData(value) {
                this.selectRow = []
                if (value.length > 0) {
                    value.forEach((item) => {
                        this.selectRow.push(this.tableData.indexOf(item))
                    })
                }
            },
            flowUpType(value) {
                this.nowPage = 1
                getFlowUp(1, 10, this.nowData.id, this.flowUpContent, this.timeSort, value).then(res => {
                    if (res.data.success) {
                        this.flowUpList = res.data.data.records
                        this.flowUpTotal = res.data.data.total
                    }
                })
            },
            timeSort(value) {
                this.nowPage = 1
                console.log(this.nowPage)
                getFlowUp(1, 10, this.nowData.id, this.flowUpContent, value, this.flowUpType).then(res => {
                    if (res.data.success) {
                        this.flowUpList = res.data.data.records
                        this.flowUpTotal = res.data.data.total
                    }
                })
            },
            '$route': function (to) {
                this.logShow = false
                this.userId = to.params.userId
                this.input = ''
                this.nowPage = 1
                this.nowSize = 10
                this.init()
                this.getMarkList()
                this.getCustType()
            },
            senior(value) {
                this.tableHeight = value ? document.documentElement.clientHeight - 227 :document.documentElement.clientHeight - 177
            }
        },
        components: {
            editCompany,
            Mail,
            drawer,
            DialogLinker,
            tableTemplate
        },
        created() {
            this.jurisdiction = this.vaildData(this.permission)
            getCustField(this.userId).then(res => { // 列表显示字段
                if (res.data.success) {
                    res.data.data.forEach(value => {
                        value.show = value.isshow == 0 ? false : true
                        if (value.show) {
                            this.checkList.push(value.name)
                            this.headerList.push(value)
                        }
                    })
                    this.showlist = res.data.data
                    this.copyCheckList = this.checkList
                    this.load = true
                }
            })

            findUserByCrop().then(res => { // 公司下所有员工
                if (res.data.success) {
                    this.userTree = res.data.data
                }
            })
            this.init()

            this.getMarkList()

            this.getCustType()

            fullNameStore().then(res => { // 输入建议
                this.tips = res.data.data
            })

        },
        mounted() {
            document.addEventListener('click', () => {
                this.cloorPickerShow = false
            })
            window.onresize = () => {
                this.$nextTick(() => {
                    this.tableHeight = this.senior ? document.documentElement.clientHeight - 227 :document.documentElement.clientHeight - 177
                })
            }
        },
        methods: {
            toDetail(id,userId){
                sessionStorage.setItem("lastpathcus", this.$route.fullPath)
                this.$router.push(`/customer/subordinateDetail/${id}`);
            },
            init() { // 初始化，获得新数据
                querySubCust(this.userId, this.$route.params.typeId, this.input, this.lables.toString(), this.typeids.toString(), this.nowPage, this.nowSize, this.sortField, this.sortType).then(res => { // 查询客户列表
                    if (res.data.success) {
                        this.tableData = res.data.data.records
                        this.total = res.data.data.total // 总页数
                        this.nowpage = res.data.data.current // 当前页数
                    }
                })
            },
            senMail() {
                if (this.common.emailList.length == 0) {
                    this.$confirm(' <div style="margin: 20px 10px;">\n' +
                        '        <p style="line-height: 30px;\n' +
                        '        font-size: 14px;">您需要先绑定自己的常用邮箱到我们的平台，才可以使用邮件模块功能哦！</p>\n' +
                        '        <p style="line-height: 30px;\n' +
                        '        font-size: 14px;">点击下方的按钮即可立即去绑定。</p>\n' +
                        '      </div>', '邮箱绑定提醒', {
                        dangerouslyUseHTMLString: true,
                        confirmButtonText: '去绑定',
                        cancelButtonText: '取 消',
                    }).then(() => {
                        this.$store.commit('SET_CURRENTSETFRAG', 'eight')
                        this.$router.push('/mail/administration');
                    }).catch(() => {
                    })
                    return;
                } else {
                    this.$refs.dialogLinker.init(this.selectData)
                }
            },
            dealingsMail() { // 来往邮件
                this.getCustomerInfo()
            },
            cancelMark() { // 标记为弹框关闭
                this.markDialog = false
                this.markArr = []
            },
            cancelLabel() { // 标签弹框关闭
                this.label_show = false
                this.markName = ''
                this.colorBg = ''
            },
            getMarkList() {
                queryCustMark(this.userId).then((res) => { // 请求标记的数组
                    this.markList = res.data.data
                    this.lableList = JSON.parse(JSON.stringify(res.data.data))
                    var obj = {
                        corpid: "000000",
                        custid: "",
                        id: -1,
                        markName: "+新建标签",
                    }
                    this.lableList.push(obj)
                })
            },
            getCustType() {
                queryCustType(this.userId).then(res => { // 当前用户的分组
                    this.custTypeOptions = res.data.data
                    this.$nextTick(() => {
                        if (this.custType != undefined) {
                            this.typeids.push(this.custType)
                        }
                    })

                })
            },
            querySearch(queryString, cb) {
                var tips = this.tips;
                console.log(tips.filter(this.createFilter(queryString)))
                var results = queryString ? tips.filter(this.createFilter(queryString)) : tips;
                // 调用 callback 返回建议列表的数据
                cb(results);
            },
            createFilter(queryString) { // 搜索框过滤
                return (restaurant) => {
                    return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },
            replace() {
                var str = this.input
                this.input = str.replace(/\<|\>/g, '')
            },
            unlabel(custId, markId) { // 取消标签
                delMarkCust(custId, markId).then((res) => {
                    if (res.data.success) {
                        this.$message({
                            type: 'success',
                            message: '删除标签成功'
                        })
                        this.init()
                    }
                })
            },
            custShow() { // 更改客户表头设置
                this.loading = true
                this.showlist.forEach((value) => {
                    if (this.copyCheckList.indexOf(value.name) > -1) {
                        value.isshow = 1 // 更改为true
                    } else {
                        value.isshow = 0 //跟改为false
                    }
                })
                setCustField(this.showlist).then(res => {
                    if (res.data.success) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        })
                        getCustField().then(res => { // 列表显示字段
                            if (res.data.success) {
                                this.checkList = []
                                this.headerList = []
                                res.data.data.forEach(value => {
                                    value.show = value.isshow == 0 ? false : true
                                    if (value.show) {
                                        this.checkList.push(value.name)
                                        this.headerList.push(value)
                                    }
                                })
                                this.$nextTick(() => {
                                    this.showlist = res.data.data
                                    this.copyCheckList = this.checkList
                                })
                            }
                        })
                        this.loading = false
                        this.centerDialogVisible = false
                    }
                }).catch(()=> {
                    this.loading = false
                })
            },

            closeCustShow() { // 取消客户表头设置
                this.centerDialogVisible = false
                this.copyCheckList = this.checkList
            },

            cancelCust() { // 取消跟进客户
                cancelFlowUp(this.selectIds.toString()).then(res => {
                    if (res.data.success) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        })
                        this.cancel_show = false
                        this.bus.$emit('updataCustMenu')
                        this.init()
                    }
                })
            },
            mergeCust() { // 合并客户
                var topid = ''
                this.selectData.forEach(value => {
                    if (value.fullname == this.priKey) {
                        topid = value.id
                    }
                })
                this.selectIds.unshift(topid)
                mergeCust(this.selectIds.toString()).then(res => {
                    if (res.data.success) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        })
                        this.bus.$emit('updataCustMenu')
                        this.signDialog = false
                        this.init()
                    }
                })
            },
            toMail() { // 跳转到往来邮件
                this.$router.push(`/mailCustomer/${this.nowData.id}`)
            },
            handleNodeClick(data) { // tree点击
                this.treeShow = false
                var ids = []
                this.selectData.forEach(value => {
                    ids.push(value.id)
                })
                moveGroup(ids.toString(), data.id).then(res => {
                    if (res.data.success) {
                        this.$message({
                            type: "success",
                            message: res.data.msg
                        })
                        this.init()
                    }
                })
            },
            sortChange(order) { // sort 排序发生变化
                switch (order.prop) {
                    case 'light':
                        this.sortField = 'Light' // 标记
                        break;
                    case 'city':
                        this.sortField = 'country_icon' // 城市
                        break;
                    case 'talkNum':
                        this.sortField = 'talk_num' // 沟通次数
                        break;
                }

                if (order.order == 'ascending') {
                    this.sortType = 'ASC'
                } else {
                    this.sortType = 'Desc'
                }
                this.init()
            },
            moveCust(item) { // 移动客户分组
                moveGroup(this.nowData.id, item.id).then(res => {
                    if (res.data.success) {
                        this.$message({
                            message: res.data.msg,
                            type: 'success'
                        })
                    }
                })
            },
            markedAs(item) { // 标记为
                if (this.markArr.includes(item.id)) {
                    this.markArr = this.markArr.filter((value) => { // 过滤数组
                        return value != item.id
                    })
                    this.markDto = this.markDto.filter((value) => { // 过滤数组
                        return value.id != item.id
                    })
                } else {
                    this.markArr.push(item.id) // 添加到数组
                    this.markDto.push({
                        "markId": item.id,
                        "markColor": item.markColor,
                        "markName": item.markName
                    })
                }
            },
            openAddMark() {
                if (this.markArr.includes(-1)) {
                    this.markArr = []
                    this.label_show = true
                    this.markDialog = false
                }
            },
            custSaveMark() {
                let arr = []
                this.selectData.forEach(value => {
                    arr.push(value.id)
                })
                if (this.markArr.length > 0) {
                    markCust(arr.toString(), this.markArr.join(',')).then(res => {
                        this.markArr = []
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        })
                        // 重新请求数据
                        this.init()
                    })
                }
                this.markDialog = false
            },
            sharedCust() { // 共享
                this.shareDialog = false
                let arr = []
                if (this.shareArr) {
                    this.selectData.forEach(value => {
                        arr.push(value.id)
                    })
                    shareCust(arr.toString(), this.shareArr.toString()).then(res => {
                        if (res.data.success) {
                            this.$message({
                                type: 'success',
                                message: res.data.msg
                            })
                            this.bus.$emit('updataCustMenu')
                            this.init()
                        }
                    })
                }
            },
            cancelShare() {
                this.shareDialog = false
                this.shareArr = []
            },
            cancelTransfer() { // 取消转移
                this.transferDialog = false
                this.transferArr = []
            },
            transferCust() { // 转移
                let arr = []
                this.transferDialog = false
                if (this.transferArr) {
                    this.selectData.forEach(value => {
                        arr.push(value.id)
                    })
                    transferCust(arr.toString(), this.transferArr.toString()).then(res => {
                        if (res.data.success) {
                            this.$message({
                                type: 'success',
                                message: res.data.msg
                            })
                            this.bus.$emit('updataCustMenu')
                            this.init()
                        }
                    })
                }
            },
            addMark() { // 新增标签
                saveCustMark(this.colorBg, this.markName, this.userId).then((res) => {
                    if (res.data.success) {
                        this.markName = ''
                        this.colorBg = ''
                        this.label_show = false

                        queryCustMark(this.userId).then((res) => { // 请求标记的数组
                            this.lableList = res.data.data
                            var nowMarkId = this.lableList[this.lableList.length - 1].id

                            var arr = []
                            this.selectData.forEach(value => {
                                arr.push(value.id)
                            })

                            markCust(arr.toString(), nowMarkId).then(res => {
                                this.markDto = []
                                this.markArr = []
                                this.$message({
                                    type: 'success',
                                    message: res.data.msg
                                })
                                // 重新请求数据
                                var obj = {
                                    corpid: "000000",
                                    custid: "",
                                    id: -1,
                                    markName: "+新建标签",
                                }
                                this.lableList.push(obj)
                                this.init()
                            })
                        })
                    }
                })
            },
            checkbox(event, value, arr) { // checktbox 点击
                if (value == 'grouping') {
                    if (this.typeids.length == arr.length) {
                        this.typeids = []
                    } else {
                        this.typeids = []
                        arr.forEach((key) => {
                            this.typeids.push(key.id)
                        })
                    }
                } else {
                    if (this.lables.length == arr.length) {
                        this.lables = []
                    } else {
                        this.lables = []
                        arr.forEach((key) => {
                            this.lables.push(key.id)
                        })
                    }
                }
                this.search() // 点击进行高级搜索
            },
            active(event, value, item) { // button 点击变色
                if (value == 'grouping') {
                    if (this.typeids.indexOf(item) > -1) {
                        this.typeids.forEach((key, index) => {
                            if (key == item) {
                                this.typeids.splice(index, 1)
                            }
                        })
                    } else {
                        this.typeids.push(item)
                    }
                } else {
                    if (this.lables.indexOf(item) > -1) {
                        this.lables.forEach((key, index) => {
                            if (key == item) {
                                this.lables.splice(index, 1)
                            }
                        })
                    } else {
                        this.lables.push(item)
                    }
                }
                this.search() // 点击进行高级搜索
            },
            star(value, index) { // 点亮改变状态
                // alert(value, index)
                let type = ''
                if (value == 0) {
                    type = 1
                } else {
                    type = 0
                }
                lightCustInfo(index, type).then(() => {
                    this.init()
                })
            },
            show_editContacts(item, index) {
                if (item) {
                    this.editCon_title = '编辑联系人'
                    this.contactsIndex = index
                    this.contactsData = item
                } else {
                    this.editCon_title = '新增联系人'
                    this.contactsData = {
                        'firstName': '',
                        'lastName': '',
                        'email': '',
                        'postType': '',
                        'telFax': ''
                    }
                    this.contactsIndex = ''
                }
                this.edittacts_show = true
            },
            search() { // 搜索
                this.nowPage = 1
                this.init()
            },
            deleteCust() { // 删除
                let removeArr = []
                this.selectData.forEach(value => {
                    removeArr.push(value.id)
                })
                deleteBatchCust(removeArr).then((res) => {
                    if (res.data.success) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        })
                        this.delete_show = false
                        this.bus.$emit('updataCustMenu')
                        this.init()
                    }
                })
            },
            selectColor(e) { // 更改颜色
                if (e.target.nodeName === 'LI') {
                    var check = document.getElementsByClassName('el-icon-check')
                    for (var i = 0; i < check.length; i++) {
                        check[i].remove()
                    }
                    var i = document.createElement('i')
                    i.className = 'el-icon-check'
                    e.target.appendChild(i)
                    this.colorBg = e.target.style.background
                }
            },
            cloorPicker(e) { // 显示颜色选择器
                e.preventDefault()
                this.cloorPickerShow = true
            },
            updataCompany(value) { // 编辑弹框的显示与隐藏
                if (value) {
                    this.init()
                }
                this.custId = ''
                this.editCom_show = false
                this.logShow = false
            },
            editlog() { // 打开客户编辑弹框
                this.logShow = true
                this.$nextTick(() => {
                    this.editCom_title = "编辑客户"
                    this.editCom_show = true
                    this.custId = this.selectData[0].id
                })
            },
            changeCheck(value) { // 设置公司名称为必选
                if (value.indexOf('客户名称') < 0) {
                    this.checkList.push('客户名称')
                }
            },
            advancedSearch() { // 高级搜索的显示与隐藏
                this.senior = !this.senior
            },
            selectList(selection) { // table的全选
                if (selection.length == 1) {
                    this.edit_boolean = false
                } else {
                    this.edit_boolean = true
                }
                this.select_num = selection.length
                this.selectData = selection
                this.selectIds = []
                this.selectName = []
                this.selectData.forEach((value) => {
                    this.selectIds.push(value.id)
                    this.selectName.push(value.fullname)
                })
                this.priKey = this.selectName[0]
            },
            rowClass({row, rowIndex}) { // table选中后的样式
                if (this.selectRow.includes(rowIndex)) {
                    return {
                        "background-color": "#E9F3FD",
                        "color": "#409EFF"
                    }
                }
            },
            handleSizeChange(size) { // 改变每页条数
                this.nowPage = 1
                this.nowSize = size
                this.init()
            },
            handleCurrentChange(page) {
                this.nowpage = page // 当前页设置
                this.init()
            },
            showlog() { // 客户的显示
                this.logShow = true
                this.$nextTick(() => {
                    this.editCom_title = "新增客户"
                    this.editCom_show = true
                    this.typeId = this.custType
                    this.custId = ''
                    this.$refs.editCompany.getInit();
                })
            },
            //获取客户信息
            getCustomerInfo() {
                queryCust(this.selectIds[0]).then(res => {
                    if (res.data.success) {
                        let link = res.data.data.custLinkDtos;
                        let result = []
                        if (link.length > 0) {
                            link.map(item => {
                                result.push(item.email)
                            })
                            getCustomerEmail(result,{userId:this.$route.params.userId},0);//获取往来邮件
                        } else {//没有邮箱 - 不需要跳转
                            this.$message({
                                message: '该用户未绑定邮箱，暂无往来邮件',
                                type: "success"
                            });
                        }
                    }
                })
            },
            preview(item, column, event) { // 右侧抽屉打开
                if (event.target.tagName !== 'I') {
                    this.nowId = item.id
                    this.visShow = true
                    this.drawerShow = true
                }
            },
            closeDrawer() {
                this.visShow = false
                this.drawerShow = false
            },
            floeUpChangePage(page) { // 跟进记录翻页
                this.nowPage = page
                getFlowUp(page, 10, this.nowData.id, this.flowUpContent, this.timeSort, this.flowUpType).then(res => {
                    if (res.data.success) {
                        this.flowUpList = res.data.data.records
                        this.flowUpTotal = res.data.data.total
                    }
                })
            },
            searchFlowUp() {
                this.nowPage = 1
                getFlowUp(1, 10, this.nowData.id, this.flowUpContent, this.timeSort, this.flowUpType).then(res => {
                    if (res.data.success) {
                        this.flowUpList = res.data.data.records
                        this.flowUpTotal = res.data.data.total
                    }
                })
            }
        },

    }
</script>

<style lang="scss">
  .custBox {
    .el-table__header-wrapper {
      background: rgb(234, 240, 246);
      height: 35px;
      line-height: 35px;
    }
  }

  .el-table__header {
    width: 100% !important;
  }

  .el-table__body {
    width: 100% !important;
  }

  .cell {
    .el-rate__icon {
      font-size: 18px;
    }
  }

  .tag {
    .el-icon-close {
      color: white !important;
    }
  }
</style>


<style lang="scss" scoped>
  @import "../../styles/customer";
</style>


